<?php
/**
 * Created by PhpStorm.
 * User: Digvijay
 * Date: 3/22/14
 * Time: 3:52 PM
 */

class Petrostock extends MY_Controller {

    function index() {
        $data = array("filename" => "Solid Petro-Stock");
        $this->load->view("petrostock", $data);
    }

    function add() {
        $recentPetroStock = $this->findRecent("Solidpetrostock");
        $solidPetro = new Solidpetrostock();
        if ($recentPetroStock != null) {
            $solidPetro->setOpeningStock($recentPetroStock->getClosingStock());
            $solidPetro->setClosingStock($recentPetroStock->getClosingStock());
        } else {
            $solidPetro->setOpeningStock(0);
            $solidPetro->setClosingStock(0);
        }
        $grades = $this->findAll("SPGrade");
        $data = array("filename" => "Solid Petro-Stock", "module" => "Add", "petroStock" => $solidPetro, "grades" => $grades);
        $this->load->view("addpetrostock", $data);
    }

    function edit($id = null) {
        $petroStock = null;
        if ($id != null) {
            $petroStock = $this->findById("Solidpetrostock", $id);
        }
        $grades = $this->findAll("SPGrade");
        $data = array("filename" => "Solid Petro-Stock", "module" => "Edit", "petroStock" => $petroStock, "grades" => $grades);
        $this->load->view("addpetrostock", $data);
    }

    function get() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $endDate = new DateTime();
        $endDate = $endDate->format("d-m-Y");
        $startDate = new DateTime();
        $startDate = "1-" . $startDate->format("m-Y");
        $solidPetroStocks = $this->getDataFor("Solidpetrostock", $startDate, $endDate, "ASC");
        echo json_encode($solidPetroStocks);
    }

    function getDataForDates() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $from = trim($this->input->post('dateFrom'));
        $to = trim($this->input->post('dateTo'));
        $reportData = $this->getDataFor("Solidpetrostock", $from, $to, "ASC");
        echo json_encode($reportData);
    }

    function persist() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        $response->setStatus(false);
        $needToUpdateLaterRecords = false;
        $description = "";
        try {
            $id = trim($this->input->post('id'));
            $date = new DateTime(trim($this->input->post('date')));
            $grade = $this->findById("SPGrade", trim($this->input->post('grade')));
            $openingStock = trim($this->input->post('openingStock'));
            $purchaseAndProduction = trim($this->input->post('purchaseAndProduction'));
            $salesAndConsumption = trim($this->input->post('salesAndConsumption'));
            $closingStock = trim($this->input->post('closingStock'));
            $solidPetroStock = null;

            //Adding New Record.
            if ($id == null || $id == "") {
                $solidPetroStock = new Solidpetrostock();
                $solidPetroStock->setDate($date);
                $solidPetroStock->setGrade($grade);
                $solidPetroStock->setPurchaseAndProduction($purchaseAndProduction);
                $solidPetroStock->setSaleAndConsumption($salesAndConsumption);

                //Check if Record is In-Between existing Records.
                if (count($this->findGreaterThanDate($date, "Solidpetrostock", "asc")) > 0) {
                    $lastRecentRecord = $this->findRecentForDate($date, "Solidpetrostock");
                    if ($lastRecentRecord == null) {
                        $lastRecentRecord = $this->findEqualsOrLessThanDate($date, "Solidpetrostock", "desc");
                        $lastRecentRecord = count($lastRecentRecord) > 0 ? $lastRecentRecord[0] : null;
                    }
                    if ($lastRecentRecord != null) {
                        $oStock = $lastRecentRecord->getClosingStock();
                        $solidPetroStock->setOpeningStock($oStock);
                        $solidPetroStock->setClosingStock(($oStock - $purchaseAndProduction) + $salesAndConsumption);
                        $needToUpdateLaterRecords = true;
                    } else {
                        $response->setErrorMessage("Not able to Add Record, as record with later date exist");
                        echo json_encode($response);
                        return;
                    }

                } else {
                    //NOTE: Double check to make sure proper values for Closing and Opening stock are update.
                    //Cannot trust clients auto-calculated values for Opening and Closing stock.
                    $recentSolidPetroStock = $this->findRecent("Solidpetrostock");
                    if ($recentSolidPetroStock != null) {
                        $sOpeningStock = $recentSolidPetroStock->getClosingStock();
                        $sClosingStock = ($sOpeningStock + $solidPetroStock->getSaleAndConsumption()) - $solidPetroStock->getPurchaseAndProduction();
                        $solidPetroStock->setClosingStock($sClosingStock);
                        $solidPetroStock->setOpeningStock($sOpeningStock);
                    } else {
                        //This is Probably 1st Record In Database.
                        $solidPetroStock->setOpeningStock(0);
                        $solidPetroStock->setClosingStock($salesAndConsumption - $purchaseAndProduction);
                    }
                }
                $response->setMessage("Saved");
                $description = "Added Solid Petro-stock record for " . $date->format('d-m-y');
            }
            //If Editing existing Record.
            if ($id != null || $id != "") {
                $solidPetroStock = $this->findById("Solidpetrostock", $id);

                $solidPetroStock->setDate($date);
                $solidPetroStock->setGrade($grade);
                $solidPetroStock->setPurchaseAndProduction($purchaseAndProduction);
                $solidPetroStock->setSaleAndConsumption($salesAndConsumption);
                $solidPetroStock->setClosingStock(($solidPetroStock->getOpeningStock() - $purchaseAndProduction) + $salesAndConsumption);

                $response->setMessage("Updated");
                $description = "Updated Solid Petro-stock record for " . $date->format('d-m-y');
                $needToUpdateLaterRecords = true;
            }

            //Register User Activity and Save/Update record.
            $solidPetroStock->setUserId($this->getLoggedInUser()->getId());
            parent::save($solidPetroStock);

            // If record is from In-Between existing records then Need to update all later records opening and closing stock.
            if ($needToUpdateLaterRecords) {
                $previousSpsRecord = $solidPetroStock;
                $laterSolidPetroStocks = $this->findGreaterThanDate($date, "Solidpetrostock", "asc");
                foreach ($laterSolidPetroStocks as $laterSpsRecord) {
                    $pClosingStock = $previousSpsRecord->getClosingStock();
                    $laterSpsRecord->setOpeningStock($pClosingStock);
                    $pClosingStock = $pClosingStock + $laterSpsRecord->getSaleAndConsumption();
                    $pClosingStock = $pClosingStock - $laterSpsRecord->getPurchaseAndProduction();
                    $laterSpsRecord->setClosingStock($pClosingStock);
                    parent::save($laterSpsRecord);
                    $previousSpsRecord = $laterSpsRecord;
                }
            }
            $response->setStatus(true);
            $this->registerUserActivty($description);
        } catch (Exception $e) {
            $response->setErrorMessage($e->getMessage());
        }
        echo json_encode($response);
    }
} 